import 'dart:async';

import 'package:common_utils/common_utils.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/pages/mall_app/account_safe_phone/state.dart';
import 'package:yp/services/api.dart';

import '../../../helper.dart';
import '../../../router.dart';

class ModifyPhoneLogic extends GetxController {
  final state = ModifyPhoneState();

  @override
  void onInit() {
    super.onInit();
    state.oldCode = Get.arguments['code'];
    state.oldToken = Get.arguments['token'];
  }

  //请求发送验证码
  void sendSms() {
    print(state.phoneCtrl.text);
    if (state.phoneCtrl.text.isEmpty) {
      toast("请输入手机号");
      return;
    }
    if (!RegexUtil.isMobileSimple(state.phoneCtrl.text)) {
      toast("手机号格式错误");
      return;
    }
    if (state.phoneCtrl.text == SpUtil.getString('number')) {
      toast("请输入新手机号");
      return;
    }
    if (!state.verifyEnable) {
      return;
    }
    state.verifyEnable = false;
    var params = {
      "mobile": state.phoneCtrl.text,
      "verify_code_type": "memBindCode"
    };
    Api.sendSms(params).listen((event) {
      if (event['code'] == 0) {
        toast("验证码已发送,请注意查收");
        state.smsData = event;
      } else {
        toast(event['message']);
        state.verifyEnable = true;
      }
      update();
    });

    state.timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (state.seconds == 0) {
        state.timer?.cancel();
        state.verifyText = '重新发送';
        state.seconds = 5;
        state.verifyEnable = true;
        update();
        return;
      }
      state.verifyEnable = false;
      state.seconds = --state.seconds;
      state.verifyText = "已发送${state.seconds}s";
      print("已发送${state.seconds}s");
      update();
    });
  }

  submit() {
    if (state.phoneCtrl.text.isEmpty) {
      toast("请输入手机号");
      return;
    }
    if (!RegexUtil.isMobileSimple(state.phoneCtrl.text)) {
      toast("手机号格式错误");
      return;
    }
    if (state.phoneCtrl.text == SpUtil.getString('number')) {
      toast("请输入新手机号");
      return;
    }
    if (state.codeCtrl.text.isEmpty) {
      toast("请输入验证码");
      return;
    }

    if (state.smsData == null) {
      toast("请先获取验证码");
      return;
    }
    Get.toNamed(RouteConfig.modifyPhoneSure, arguments: {
      'phone': state.phoneCtrl.text,
      'code': state.codeCtrl.text,
      'token': state.smsData['token'],
      'oldToken': state.oldToken,
      'oldCode': state.oldCode
    });
  }

  @override
  void dispose() {
    super.dispose();
    state.timer.cancel();
  }
}
